package com.imagefake.util;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author wj
 * 七牛云云存储工具类
 */
@Slf4j
public class QiniuUtil {
    //账号的ACCESS_KEY和SECRET_KEY
    private static final String ACCESS_KEY = "OxnyJ5TvhE-Ckfe0PMaXbHBuxdZQoJoZGcqoz00R";
    private static final String SECRET_KEY = "8yJchyKgXx5DVH9QGcnrip2ZCVJrRqwggd-IznjQ";

    //云存储空间
    private static final String bucket = "image-fake"; //对应要上传到七牛云上的空间名
    private static final String path = "sd0sm6h28.hn-bkt.clouddn.com";//CDN 测试域名，该域名三十天后失效，到时候需修改
    private static final String folder = "test001/";//要上传到空间内的那个文件夹

    //密钥配置
    private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    //创建上传对象
    private static UploadManager uploadManager = new UploadManager(new Configuration());

    public static String upload(File file) {
        try {
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
            String uploadFileName = folder+"image_fake-"+simpleDateFormat.format(date)+ UUID.randomUUID();
            //调用put方法上传
            Response res = uploadManager.put(file, uploadFileName, auth.uploadToken(bucket));
            //打印返回的信息
            log.info(res.bodyString());
            return "http://"+path+"/"+uploadFileName;
        } catch (QiniuException e) {
            log.error(e.getMessage());
            return "";
        }
    }
}
